package com.example.basic.controller;

import com.example.basic.controller.dto.FileDTO;
import com.example.basic.controller.dto.SocketPayloadDTO;
import com.example.basic.domain.Games;
import com.example.basic.service.TestService;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;
import java.util.Map;

/**
 * @author mjw
 * @date 2023/8/28
 */
@RestController
@RequestMapping("/test")
public class TestController {

    private final TestService testService;

    public TestController(TestService testService) {
        this.testService = testService;
    }

    @GetMapping("/syncTest")
    public String syncTest() throws InterruptedException {
        System.out.println("开始执行------>");
        // 模拟业务逻辑
        testService.syncTest();
        System.out.println("执行完毕------>");
        return "success!";
    }


    @GetMapping("/testTransaction")
    public void testTransaction() {
        testService.testTransaction();
    }


    @GetMapping("/openUrl")
    public void openUrl(HttpServletResponse response) {
        testService.openUrl(response);
    }

    @PostMapping("/validate-template")
    public Map<Integer, Map<Integer, String>> validateTemplate(HttpServletResponse response, MultipartFile excel) {
        return testService.validateTemplate(response, excel);
    }

    @GetMapping("/rest-apis")
    public String testApis() {
        return testService.testApis();
    }

    @PostMapping("/valid-games")
    public List<String> validGames(@RequestBody Games games, BindingResult bindingResult) {
        return testService.validGames(games, bindingResult);
    }

    @PostMapping("/valid-json")
    public String validJson(@RequestBody Games games) {
        System.out.println("games:" + games);
        return testService.validJson(games);
    }

    @GetMapping("/okhttp/download")
    public void download(HttpServletRequest request, HttpServletResponse response) {
        testService.download(request, response);
    }

    @PostMapping("/download")
    public void downloadPdf(HttpServletResponse response,
                            @RequestParam("fileUrl") String fileUrl) {
        testService.downloadPdf(response, fileUrl);
    }

    @PostMapping("/download-zip")
    public void downloadZip(HttpServletResponse response,
                            @RequestBody List<FileDTO> fileDTOList) {
        testService.downloadZip(response, fileDTOList);
    }

    @PostMapping({"/socket/invoke"})
    public String socketInvoke(@RequestBody SocketPayloadDTO dto) {
        return testService.socketInvoke(dto);
    }

    @PostMapping("/to-base-byte")
    public String fileToBase64(
            MultipartFile file) {
        // 强制校验参数是否存在
        if (file == null || file.isEmpty()) {
            return "file is null";
        }
        try {
            // 核心转换逻辑
            String base64 = Base64.getEncoder().encodeToString(file.getBytes());
            System.out.println("baese64:--->" + base64);
            byte[] bytes = Base64.getDecoder().decode(base64);
            System.out.println("bytes--->" + new String(bytes, StandardCharsets.UTF_8));
            return base64;

        } catch (IOException e) {
            return "failed";
        }

        /**
         * 根据URL下载二进制文件
         * @param fileUrl
         * @return
         * @throws Exception
         */
//        public static byte[] downloadFromUrl(String fileUrl) throws Exception {
//            URL url = new URL(fileUrl);
//            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//            connection.setConnectTimeout(5000);  // 5秒连接超时
//            connection.setReadTimeout(30000);   // 30秒读取超时
//            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
//                log.error("HTTP错误代码: " + connection.getResponseCode());
//            }
//            try (InputStream in = connection.getInputStream();
//                 ByteArrayOutputStream out = new ByteArrayOutputStream()) {
//                byte[] buffer = new byte[4096];
//                int bytesRead;
//                while ((bytesRead = in.read(buffer)) != -1) {
//                    out.write(buffer, 0, bytesRead);
//                }
//                return out.toByteArray();
//            } finally {
//                connection.disconnect();
//            }
//        }
    }

}
